from tkinter import *
import os
import subprocess
import re

def hello():
    print ("hello!")
def about():
    window = Toplevel(root)
    window.iconbitmap('ac.ico')
    ProgramName = Label(window, text="Auto-Chlor Line Monitor", font="arial 10 bold")
    ProgramName.pack(side=TOP)
    versionNumber = Label(window, text="V 1.0",font = "fixedsys 12 bold ")
    versionNumber.pack(side=TOP)
    abouttext1 = Label(window, text="Software used to monitor status of branches public IP and router status",font = "Times 12")
    abouttext1.pack(side=TOP)
    abouttext2 = Label(window, text="Developed using Python and Tkinter library", font = "Times 12")
    abouttext2.pack(side=TOP)
    signature = Label(window, text="Jasmit Kakkar - Junior Network Engineer", font = "arial 10 italic")
    signature.pack(side=TOP)


def drawMenu(root):
    menubar = Menu(root)
    # create a pulldown menu, and add it to the menu bar
    filemenu = Menu(menubar, tearoff=0)
    filemenu.add_command(label="Open", command=hello)
    filemenu.add_command(label="Save", command=hello)
    filemenu.add_separator()
    filemenu.add_command(label="Exit", command=root.quit)
    menubar.add_cascade(label="File", menu=filemenu)

    # create more pulldown menus
    editmenu = Menu(menubar, tearoff=0)
    editmenu.add_command(label="Cut", command=hello)
    editmenu.add_command(label="Copy", command=hello)
    editmenu.add_command(label="Paste", command=hello)
    menubar.add_cascade(label="Edit", menu=editmenu)

    statisticsmenu = Menu(menubar, tearoff=0)
    statisticsmenu.add_command(label="110", command=about)
    statisticsmenu.add_command(label="120", command=about)
    statisticsmenu.add_command(label="130", command=about)
    statisticsmenu.add_command(label="140", command=about)
    statisticsmenu.add_command(label="...", command=about)
    menubar.add_cascade(label="Statistics", menu=statisticsmenu)

    helpmenu = Menu(menubar, tearoff=0)
    helpmenu.add_command(label="About", command=about)
    menubar.add_cascade(label="Help", menu=helpmenu)

    # display the menu
    root.config(menu=menubar)

def onFrameConfigure(canvas):
    '''Reset the scroll region to encompass the inner frame'''
    canvas.configure(scrollregion=canvas.bbox("all"))
def readBranches(filepath):
    file = open(filepath, 'r')
    branchList = {}
    for line in file.readlines():
        values = line.split()
        branchList[values[0]] = values[1]
    file.close()
    return branchList

def threaded_pingBranch(branch, wanIP):
    global framecolor
    pingresult = subprocess.Popen('ping -n 1 ' + wanIP, stdout=subprocess.PIPE, shell=True)
    (output, err) = pingresult.communicate()
    status = pingresult.wait()

    routerIP = "10.10." + branch[:-1] + ".254"
    # routerresult = subprocess.Popen('ping -n 1 ' + routerIP, stdout=subprocess.PIPE, shell=True)
    # routerresult.wait()
    # routeroutput = routerresult.poll()
    routeroutput = 1

    print(branch, ": ", output)


    printline = extractData(branch, output)

    labelframe = LabelFrame(frame, bg=framecolor, height=10)
    labelframe.pack_propagate(0)
    labelframe.pack(fill=BOTH, expand=0)
    branch = Label(labelframe, bg=framecolor, text=branch + ":", width=7, font="arial 10 bold", anchor=W).grid(column=0, row=0,padx=(15, 0))
    latency = Label(labelframe, bg=framecolor, text=getTime(output, 1), font="arial 10 bold", width=9).grid(column=1,row=0,padx=(0, 0))
    bar = Label(labelframe, bg=framecolor, text=drawBar(int(getTime(output, 0))), width=90, font="arial 10 bold",anchor=W).grid(column=2, row=0, padx=(40, 0))

    if routeroutput == 1:
        router = Label(labelframe, bg=framecolor, image=greenImage, width=150, anchor=W).grid(column=3, row=0)
    else:
        router = Label(labelframe, bg=framecolor, image=redImage, width=10, anchor=W).grid(column=3, row=0)

    if framecolor == "#91FFFF":
        framecolor = "white"
    else:
        framecolor = "#91FFFF"
    frame.update()

def pingBranches(branchList):
    global framecolor
    for key, value in branchList.items():
        pingresult = subprocess.Popen('ping -n 1 ' + value, stdout=subprocess.PIPE, shell=True)
        (output, err) = pingresult.communicate()
        status = pingresult.wait()

        routerIP = "10.10." + key[:-1] + ".254"
        #routerresult = subprocess.Popen('ping -n 1 ' + routerIP, stdout=subprocess.PIPE, shell=True)
        #routerresult.wait()
        #routeroutput = routerresult.poll()
        routeroutput = 1

        print(key, ": ", output)
        # print("Command exit status/return code : ", status)

        printline = extractData(key, output)

        #frame.insert(END, printline)
        #frame.pack(side = LEFT, fill = BOTH)
        #line = Label(frame, text=printline)
        labelframe = LabelFrame(frame, bg=framecolor, height=10)
        #labelframe.grid(column=0, row=7)
        labelframe.pack_propagate(0)
        labelframe.pack(fill=BOTH, expand=0)
        branch = Label(labelframe, bg=framecolor, text=key+":", width = 7, font = "arial 10 bold",anchor=W).grid(column=0, row=0, padx=(15,0))
        latency = Label(labelframe, bg=framecolor, text = getTime(output, 1), font="arial 10 bold", width = 9).grid(column=1, row=0, padx=(0,0))
        bar = Label(labelframe, bg=framecolor, text=drawBar(int(getTime(output, 0))), width = 90, font="arial 10 bold", anchor=W).grid(column=2, row=0, padx=(40,0))

        if routeroutput == 1:
            router = Label(labelframe, bg=framecolor, image=greenImage, width = 150,anchor=W).grid(column=3, row=0)
        else:
            router = Label(labelframe, bg=framecolor, image=redImage, width = 10, anchor=W).grid(column=3, row=0)

        if framecolor == "#91FFFF":
            framecolor = "white"
        else:
            framecolor = "#91FFFF"

        #drawRouters(routeroutput)

        frame.update()

#returns latency from raw ping output data,
#outputType = 1      this will return the latency in string formatting
#outputType = 0      this will return the latency in integer formatting
def getTime(output, outputType):
    output = str(output)
    if output.find("Request timed out") != -1:
        if outputType == 1:
            return "TIMEOUT"
        else:
            return 0
    a = output.find("time")
    time = output[a + 5:]
    time = time.split()
    time = time[0]
    time = time[:-2]
    if outputType == 1:
        return str(time)+"ms"
    else:
        return time

def extractData(branch, output):
    output = str(output)
    a = output.find("time")

    pingtime = output[a + 5:]
    pingtime = pingtime.split()
    pingtime = pingtime[0]
    pingtime = pingtime[:-2]

    printline = "     "+branch + ":                  " + pingtime
    if output.find("Request timed out") != -1:
        printline = "     "+branch + ":                  "+"TIMEOUT"
    else:
        bar = drawBar(int(pingtime))
        printline = printline + bar
    routerstatus = 1
    return printline

def drawBar(time):
    if time == 0:
        return ">>|"
    barlength = 5
    bar = ">>"
    for x in range(time, -1, -barlength):
        bar += "="
    bar += "|"
    return bar

def drawRouters(status):
    if status == 0:
        green = Label(routerList, image = greenImage)
        green.pack()
    else:
        red = Label(routerList, image=redImage)
        red.pack()






root = Tk()
root.iconbitmap('ac.ico')
root.title('Auto-Chlor Line Monitor')
#root.geometry("1100x950")
root.geometry("1100x800")

drawMenu(root)

header = Label(root, bg="gray", fg="white", text="   Branch       Latency(ms)            0                                100                                200                                300                                400                       ROUTER", font="arial 10 bold",anchor=W,justify=LEFT)
header.pack(fill='both')

greenImage = PhotoImage(file="green.gif")
redImage = PhotoImage(file="red.gif")
filepath = "branchList.txt"
framecolor = "#91FFFF"

canvas = Canvas(root, borderwidth=0, background="#ffffff")
frame = Frame(canvas, background="#ffffff")
vsb = Scrollbar(root, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=vsb.set)

vsb.pack(side="right", fill="y")
canvas.pack(side="left", fill="both", expand=True)
canvas.create_window((4,4), window=frame, anchor="nw")

frame.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))

branchList = readBranches(filepath)
pingBranches(branchList)

root.mainloop()